package cn.edu.lit.jsjxy.CourseExample.chapter8;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import cn.edu.lit.jsjxy.CourseExample.R;

public class SharedPrefsTestActivity extends AppCompatActivity implements View.OnClickListener
{
    Button btnRead, btnWrite;
    EditText etUsername,etpasswd;
    TextView tvMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_prefs_test);

        btnRead = findViewById(R.id.btnRead);
        btnWrite = findViewById(R.id.btnWrite);
        etUsername = findViewById(R.id.etUser);
        etpasswd = findViewById(R.id.etPasswd);

        tvMessage = findViewById(R.id.tvRead);

        btnWrite.setOnClickListener(this);
        btnRead.setOnClickListener(this);
    }

    @Override
    public void onClick(View view)
    {
        SharedPreferences prefs = getSharedPreferences("info",
                MODE_PRIVATE);

        switch (view.getId()) {
            case R.id.btnRead:
                String strInfo;

                if (!prefs.contains("username") || !prefs.contains("passwd"))
                {
                    Toast.makeText(this, "未找到数据", Toast.LENGTH_SHORT).show();
                    return;
                }

                String username = prefs.getString("username", null);
                String passwd = prefs.getString("passwd", null);

                strInfo = username + " : " + passwd;
                tvMessage.setText(strInfo);

                break;
            case R.id.btnWrite:

                SharedPreferences.Editor editor = prefs.edit();

                //editor.putString("userinfo", etMessage.getText().toString());
                editor.putString("username", etUsername.getText().toString());
                editor.putString("passwd", etpasswd.getText().toString());
                editor.remove("userinfo");


                editor.commit();

                break;

        }
    }
}
